package share

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"qbl_spider/slog"
	"strings"
)

/*
* @Auther:create by hjx
* @Email :1245863260@qq.com g1245863260@gmail.com
* @Date  :2021/4/5 22:41
 */

func CheckStringIsNil(strs ...string) {
	for _, str := range strs {
		if strings.Trim(str, " ") == "" {
			slog.Slog.Logger.Println(slog.Error, str, "is nil ,exit 2")
			os.Exit(2)
		}
	}
}

func CreateDir(folder string) error {
	if _, err := os.Stat(folder); err != nil {
		switch {
		case os.IsNotExist(err):
			if mkError := os.MkdirAll(folder, os.ModePerm); mkError != nil {
				slog.Slog.Logger.Println(slog.Error, "can not mkdir the old folder", folder)
				return fmt.Errorf("can not mkdir the old folder %s", folder)
			} else {
				slog.Slog.Logger.Println(slog.Info, "Created", folder, "successfully")
				return nil
			}
		case !os.IsNotExist(err):
			if rmError := os.RemoveAll(folder); rmError != nil {
				slog.Slog.Logger.Println(slog.Error, "can not remove the old folder", folder)
				return fmt.Errorf("can not remove the old folder %s", folder)
			}
			if mkError := os.MkdirAll(folder, os.ModePerm); mkError != nil {
				slog.Slog.Logger.Println(slog.Error, "can not mkdir the old folder", folder)
				return fmt.Errorf("can not mkdir the old folder %s", folder)
			} else {
				slog.Slog.Logger.Println(slog.Info, "Created", folder, "successfully")
				return nil
			}
		default:
			return nil
		}
	} else {
		slog.Slog.Logger.Println(slog.Info, "Working path", folder, "already exists")
	}
	return nil
}

func GetUrlContentString(target string) (string, error) {
	resp, err := http.Get(target)
	if err != nil {
		return "" ,err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "" ,err
	}
	return string(body),nil
}
